package org.kumas.sgrpc.remoting.transport.dispatcher;

import java.util.concurrent.ExecutorService;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.common.extension.ExtensionLoader;
import org.kumas.sgrpc.common.threadpool.manager.ExecutorRepository;
import org.kumas.sgrpc.remoting.Channel;
import org.kumas.sgrpc.remoting.ChannelHandler;
import org.kumas.sgrpc.remoting.RemotingException;
import org.kumas.sgrpc.remoting.transport.ChannelHandlerDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author KumasZhang
 * @version 1.0
 * @since 2021-07-13 15:18
 */
public class WrappedChannelHandler implements ChannelHandlerDelegate {

    protected static final Logger logger = LoggerFactory.getLogger(WrappedChannelHandler.class);
    protected final ChannelHandler handler;

    protected final URL url;

    public WrappedChannelHandler(ChannelHandler handler, URL url) {
        this.handler = handler;
        this.url = url;
    }

    public void close() {

    }

    @Override
    public ChannelHandler getHandler() {
        if (handler instanceof ChannelHandlerDelegate) {
            return ((ChannelHandlerDelegate) handler).getHandler();
        } else {
            return handler;
        }
    }

    @Override
    public void connected(Channel channel) throws RemotingException {
        handler.connected(channel);
    }

    @Override
    public void disconnected(Channel channel) throws RemotingException {
        handler.disconnected(channel);
    }

    @Override
    public void sent(Channel channel, Object message) throws RemotingException {
        handler.sent(channel, message);
    }

    @Override
    public void received(Channel channel, Object message) throws RemotingException {
        handler.received(channel, message);
    }

    @Override
    public void caught(Channel channel, Throwable exception) throws RemotingException {
        handler.caught(channel, exception);
    }

    public URL getUrl() {
        return url;
    }

    public ExecutorService getSharedExecutorService() {
        ExecutorRepository executorRepository =
            ExtensionLoader.getExtensionLoader(ExecutorRepository.class).getDefaultExtension();
        ExecutorService executor = executorRepository.getExecutor(url);
        if (executor == null) {
            executor = executorRepository.createExecutorIfAbsent(url);
        }
        return executor;
    }
}
